<template>
	<view>
		<view class="page-content">
			<view @tap="orderbyChange" :class="{'text-theme': hasChoose}">
				<button type="primary" class="topfixed-active" style="background-color: #007aff;" >筛选</button>
			</view>
			<fjj-condition ref='condition' @touchmove.stop :color="color" :list="menuList" @result="resultConditon" />
		</view>
		<uni-section title="工作记录" type="line"></uni-section>
		<view class="content">
			<uni-list style="width:100%">
				<uni-collapse>
					<text class="tips" v-if="isEmptyObject(listData[0])">无工作记录！</text>
					<uni-collapse-item
					open="true"
					:title="key + '   共有 ' + v.length + ' 条工作记录'" 
					:show-animation="true" 
					style="margin-left: 20rpx;"
					v-for="(v,key) in listData[0]" :key="key">
						<uni-swipe-action>
							<uni-swipe-action-item v-for="item in v"
							:key="item.workList.id"
							:right-options="options" 
							:show="isOpened" 
							:auto-close="true" 
							@change="change" 
							@click="bindClick($event,item.workList)">
								<uni-list-chat
								:key="item.workList.id" 
								:avatar="item.imageList.length > 0 ? item.imageList[0].url : noImage"
								:title="item.workList.name" 
								:note="item.workList.workStatus == 'EXTWORK' ? '加班' : '' + item.workStatus == 'ERRAND' ? '出差' : ''" 
								:time="item.workList.workDate" 
								:clickable="true" 
								:badge-text="item.workList.cost == null ? 0 : item.workList.cost + '元'" 
								@click="goDetail(item.workList)"></uni-list-chat>
							</uni-swipe-action-item>
						</uni-swipe-action>
					</uni-collapse-item>
				</uni-collapse>
			</uni-list>
			<view class="uni-loadmore" v-if="showLoadMore">{{loadMoreText}}</view>
			<uni-fab
			ref="fab" 
			:pattern="fab.pattern" 
			:content="fab.content" 
			:horizontal="fab.horizontal" 
			:vertical="fab.vertical" 
			:direction="fab.direction" 
			@trigger="trigger" 
			@fabClick="fabClick" />
		</view>
	</view>
</template>

<script>
	export default {
		components: {},
		data() {
			return {
				count: 0,
				page: 1,
				UNITS: {
					'年': 31557600000,
					'月': 2629800000,
					'天': 86400000,
					'小时': 3600000,
					'分钟': 60000,
					'秒': 1000
				},
				noImage: '/static/noImage.png',
				isFromIndex: false,
				projectId: '',
				listData: [],
				loadMoreText: "加载中...",
				showLoadMore: false,
				isOpen: "none",
				fab: {
					horizontal: 'left',
					vertical: 'bottom',
					direction: 'horizontal',
					pattern: {
						color: '#7A7E83',
						backgroundColor: '#fff',
						selectedColor: '#7A7E83',
					},
					content: [{
							url: '/pages/new/project-new-edit',
							iconPath: '/static/new-project.png',
							selectedIconPath: '/static/new-project.png',
							text: '工程',
							active: false
						},
						{
							url: '/pages/new/work-list-new-edit',
							iconPath: '/static/new-work-list.png',
							selectedIconPath: '/static/new-work-list.png',
							text: '工作',
							active: false
						}
					]
				},
				options: [{
						text: '编辑',
						style: {
							backgroundColor: '#007aff'
						}
					},
					{
						text: '删除',
						style: {
							backgroundColor: '#dd524d'
						}
					}
				],
				color: "#007aff",
				projects: [],
				employee: [],
				teams: [],
				hasChoose: false,
				menuList: [{
					'title': '日期范围',
					'type': 'range',
					'key': 'date',
				},{
					'title': '团队',
					'type': 'custom',
					'key': 'teams',
					'isMutiple': true, //单选
					'detailList': [],
				},{
					'title': '项目',
					'type': 'custom',
					'key': 'projects',
					'isMutiple': true, //单选
					'detailList': [],
				},{
					'title': '工作人员',
					'type': 'custom',
					'key': 'employee',
					'isMutiple': true, //多选
					'detailList': [],
				}],
			}
		},
		onLoad() {
			this.getProject();
			this.getEmployee();
			this.getTeam();
		},
		onShow() {
			if(!this.$dry.isLogin()) {
				uni.showModal({
					title: "信息",
					content: "需要登录后查看，去登录",
					showCancel: false,
					confirmText: "确定",
					success: function (res) {
						if (res.confirm) {
							uni.switchTab({
								url: '../user/user',
							})
						}
					}
				});
			}
			this.initData();
		},
		onPullDownRefresh() {
			setTimeout(() => {
				this.initData();
				uni.stopPullDownRefresh(); 
			}, 300);
		},
		onReachBottom() {
			if (this.listData[0].length < this.count) { //这里改版后判定有问题
				this.showLoadMore = true;
				this.page++; // TODO 
				this.getWorkList(this.projectId);
			}
			this.loadMoreText = "没有更多数据了!"
			return;	
		},
		onShareAppMessage(res) {
		    if (res.from === 'button') {// 来自页面内分享按钮
		      console.log(res.target)
		    }
		    return {
		      title: '大家都在用这款小工具管理项目，快来试试吧！！！',
		      path: '/pages/index/index'
		    }
		},
		methods: {
			initData(){
				this.listData = [];
				this.getWorkList();
			},
			change(e) {
				this.isOpened = e;
				//console.log('返回：', e);
			},
			getProject() {
				var token = this.$dry.get("token");
				var projectList = [];
				if(token) {
					var data = this.$request.run("queryProjectsByOwner",token);
					uni.request({
						url: data.url,
						method: data.method,
						header: data.header,
						data: {},
						success: data => {
							if (data.statusCode === 200) {
								projectList = data.data;
							}
							if (projectList.length != 0) {
								var newList = []
								projectList.forEach(e => {
									newList.push({
										title: e.name,
										value: e.id,
									});
								});
								this.projects = newList;
								this.menuList.forEach(m => {
									if(m.key == 'projects'){
										m.detailList = newList;
									}
								});
							}
						}
					})
				}
				
			},
			getEmployee() {
				var token = this.$dry.getToken();
				if (token) {
					var data = this.$request.run("listEmployeeByConditions", token);
					uni.request({
						url: data.url,
						method: data.method,
						header: data.header,
						data: {
							"owner": this.$dry.get("user").userId,
							"employeeStatus": 'NORMAL'
						},
						success: data => {
							if(data.statusCode === 200) {
								var worker = data.data;
								var newItems = [];
									worker.forEach(w => {
										newItems.push({
											title: w.realName == null ? w.nickName : w.realName,
											value: w.id
										})
									})
								this.employee = newItems;
								this.menuList.forEach(m => {
									if(m.key == 'employee'){
										m.detailList = newItems;
									}
								});
							}
						},
						fail: (data, code) => {
							console.log('fail' + JSON.stringify(data));
						}
					})
				}
			},
			getTeam() {
				var token = this.$dry.getToken();
				if(token) {
					var data = this.$request.run("listTeam", token);
					uni.request({
						url: data.url,
						method: data.method,
						header: data.header,
						data: {
							"isCreator": false
						},
						success: data => {
							if(data.statusCode === 200) {
								var team = data.data;
								var newItems = [];
									team.forEach(t => {
										newItems.push({
											title: t.name,
											value: t.id
										})
									})
								this.teams = newItems;
								this.menuList.forEach(m => {
									if(m.key == 'teams'){
										m.detailList = newItems;
									}
								});
							}
						}
					})
				}
			},
			bindClick(e,data) {
				var that = this;
				if(e.index == 0){
					var project_id = '';
					if(this.isFromIndex == true){
						project_id = data.projectId;
						this.isFromIndex= false;
					}
					uni.navigateTo({
						url: '../new/work-list-new-edit?id=' + data.id,
					})
				}
				else {
					uni.showModal({
						title: "信息",
						content: "确定要删除" + data.name + "吗?" + "如已有消费记录，删除该记录将会同步删除该记录的所有消费记录",
						showCancel: true,
						confirmText: "确定",
						success: function (res) {
							if (res.confirm) {
								var token = that.$dry.getToken();
								if(token){
									var delData = that.$request.run("deleteWorkListById",token);
									uni.request({
										url: delData.url,
										method: delData.method,
										header: delData.header,
										data: {
											"workListId": data.id
										},
										success: data => {
											if(data.statusCode == 200 && data.data.code == 0){
												uni.showToast({
													title: "删除成功",
													duration: 1000
												});
											}
										}
									})
								}
							}
						}
					});
				}
			},
			showLoading: function() {
				uni.showLoading({
					title: 'loading'
				});
			
				// #ifdef MP-ALIPAY
				this._showTimer && clearTimeout(this._showTimer);
				this._showTimer = setTimeout(() => {
					this.hideLoading();
				}, 3000)
				// #endif
			},
			trigger(e) {
				//console.log(e)
				this.fab.content[e.index].active = !e.item.active
				this.$refs.fab.close();
				uni.navigateTo({
					url: e.item.url
				})
			},
			fabClick() {
			// 	uni.showToast({
			// 		title: '点击了悬浮按钮',
			// 		icon: 'none'
			// 	})
			},
			hideLoading: function() {
				uni.hideLoading();
			},
			goDetail(item) {
				if(this.isFromIndex == true){
					this.$dry.set("projectId",item.projectId);
					this.isFromIndex = false;
				}
				uni.navigateTo({
					url: '../work-list/detail?id=' + item.id +'&projectId=' + item.projectId,
				})
			},
			getWorkList() {
				var token = this.$dry.getToken();
				if(token){
					var data = [];
					var queryData = {};
					var projectId = this.$dry.get("projectId");
					if(projectId){
						uni.removeStorageSync("projectId");
						data = this.$request.run("queryListByProjectId",token);
						queryData.projectId = projectId;
					} else {
						data = this.$request.run("queryAllList",token);
						queryData.owner = this.$dry.get("user").userId;
					}
				    uni.request({
				    	url: data.url,
				    	method: data.method,
				    	header: data.header,
				    	data: queryData,
						success: data => {
							var workList = data.data;
							this.count = workList.length;
							this.listData = this.listData.concat(workList);
							console.log(this.listData)
							// this.listData = [...this.listData, ...workList];
						}
					})
				}
			},
			format(dateStr) {
				var date = this.parse(dateStr)
				var diff = Date.now() - date.getTime();
				if (diff < this.UNITS['天']) {
					return this.humanize(diff);
				}
				var _format = function(number) {
					return (number < 10 ? ('0' + number) : number);
				};
				return date.getFullYear() + '-' + _format(date.getMonth() + 1) + '-' + _format(date.getDate()) + ' ' +
					_format(date.getHours()) + ':' + _format(date.getMinutes());
			},
			parse(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
				var a = str.split(/[^0-9]/);
				return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
			},
			resultConditon(obj) {
				this.$refs.condition.visibleDrawer = false;
				this.hasChoose = obj.hasChoose;
				var token = this.$dry.getToken();
				if(token){
					var data = {};
					if(obj != null) {
						if(obj.result.date.length > 0){
							data.startDate = obj.result.dateMin;
							data.endDate = obj.result.dateMax;
						}
						if(obj.result.projects != ''){
							data.projects = obj.result.projects;
						}
						if(obj.result.employee != ''){
							data.employee = obj.result.employee;
						}
						if(obj.result.teams != '') {
							data.teams = obj.result.teams;
						}
					}
				    var queryData = this.$request.run("queryWorkListByCondition", token);
				    uni.request({
				    	url: queryData.url,
				    	method: queryData.method,
				    	header: queryData.header,
				    	data: data,
						success: data => {
							this.listData = [];
							// 这样做的目的是为了在筛选完成后重新渲染
							setTimeout(() => {
								this.listData = [data.data];
							},100);
							// this.listData = [data.data];
						}
					})
				}
			},
			orderbyChange(obj) {
				this.$refs.condition.visibleDrawer = true;
			},
			isEmptyObject(e) {  
			    var t;  
			    for (t in e){
			    	return !1;  
			    }  
			    return !0  
			},
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
	
	.topfixed-active{
	    width: 100%;
	    position: fixed;
	    top: var(--window-top);
	    left: 0;
	    background: #fff;
	    z-index: 9;
	    box-sizing: border-box;
	}
	.tips{
		padding:10rpx 20rpx;
		text-align: left;
		font-size: 24rpx;
		color: #0077AA;
	}
</style>
